package com.uyayo.portal.freemarker;

import com.uyayo.cms.entity.CmsAd;
import com.uyayo.cms.model.CmsAdCondition;
import com.uyayo.cms.service.CmsAdService;
import freemarker.core.Environment;
import freemarker.ext.beans.BeansWrapper;
import freemarker.ext.beans.BeansWrapperBuilder;
import freemarker.template.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * Created by hfj
 * on 2021/3/31.
 */
public class CmsAdListDirective implements TemplateDirectiveModel {

    @Autowired
    private CmsAdService cmsAdService;

    @Override
    public void execute(Environment environment, Map params, TemplateModel[] templateModels, TemplateDirectiveBody templateDirectiveBody) throws TemplateException, IOException {

        Long adCategoryId = Long.valueOf(getParam(params,"adCategoryId","0"));
        CmsAdCondition cmsAdCondition = new CmsAdCondition();
        cmsAdCondition.setAdCategoryId(adCategoryId);
        cmsAdCondition.setStatus((short) 1);
        List<CmsAd> list = cmsAdService.selectAd(cmsAdCondition);
        environment.setVariable("cmsAdList", getBeansWrapper().wrap(list));
        templateDirectiveBody.render(environment.getOut());
    }

    public static BeansWrapper getBeansWrapper(){
        return new BeansWrapperBuilder(Configuration.VERSION_2_3_25).build();
    }


    /**
     * 获取参数值
     * @param params
     * @param key
     * @return
     * @throws TemplateException
     */
    private String getRequiredParam(Map params,String key) throws TemplateException {
        Object value = params.get(key);
        if(value == null || StringUtils.isEmpty(value.toString())) {
            throw new TemplateModelException("not found required parameter:"+key+" for directive");
        }
        return value.toString();
    }

    /**
     * 获取参数值
     * @param params
     * @param key
     * @param defaultValue
     * @return
     * @throws TemplateException
     */
    private String getParam(Map params,String key,String defaultValue){
        Object value = params.get(key);
        return value == null ? defaultValue : value.toString();
    }
}
